<template>
	<el-drawer v-model="isShowDrawer" direction="rtl" :before-close="handleClose" :size="curDrawerSize" :close-on-click-modal="isReadOnly">
		<template #header="{ titleId, titleClass }">
			<div class="zs-drawer-header" :id="titleId" :class="titleClass">
				<i class="icon-b-item zs-icon zs-text-blue zs-space-right-sm"></i>
				<div class="zs-title zs-text-black">设施</div>
			</div>
		</template>

		<template #default>
			<div class="zs-layout-flex-col zs-drawer-container">
				<div class="zs-card-sm zs-space-bottom">
					<span>
						<el-input v-model="queryParams.deviceName" class="zs-select-md zs-space-right-sm" placeholder="设施名称" clearable @blur="queryList" />
						<el-select v-model="queryParams.floorNum" class="zs-select-md zs-space-right-sm" placeholder="所属楼层" clearable filterable @change="queryList">
							<el-option v-for="item in dictObj.BUILDING_LEVEL" :key="item.id" :label="item.dictLabel" :value="item.dictValue" />
						</el-select>
						<el-input v-model="queryParams.deviceLocation" class="zs-select-md zs-space-right-sm" placeholder="设施位置" clearable @blur="queryList" />
						<el-button class="zs-btn-plain" @click="queryList" v-btnPermi="{ permis: ['p_btn_property_maintenance_facility_config_list_query'] }"> 查询 </el-button>
					</span>
				</div>

				<!-- teble -->
				<div class="zs-card zs-table-page-content zs-layout-flex-auto">
					<el-table ref="tableRef" :key="currentRow.id" class="zs-table-page-main" row-key="facilityId" :data="tableData.data" v-loading="tableData.loading" :header-checkbox-disabled="handleType == 'edit' ? true : false" stripe @selection-change="handleSelectionChange">
						<el-table-column type="selection" width="55" reserve-selection :selectable="isSelectable" />
						<el-table-column type="index" label="序号" width="60" align="center" />
						<el-table-column prop="facilityName" label="设施名称" align="left" show-overflow-tooltip />
						<el-table-column prop="facilityNum" label="设施编号" width="130" align="left" />
						<el-table-column prop="floorNum" label="楼层" width="130" align="left" />
						<el-table-column prop="facilityLocation" label="设施位置" align="left" show-overflow-tooltip />
					</el-table>
				</div>
			</div>
		</template>

		<template v-if="handleType != 'info'" #footer>
			<div>
				<el-button class="zs-btn-md zs-btn-primary" @click="doConfirm">提交</el-button>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
	import { planFacilityListApi, planFacilityBindApi } from '@/api/facility.js';
	import { ref, reactive, nextTick, watch } from 'vue';
	import { ElMessage } from 'element-plus';
	import { useStore } from 'vuex';
	import { useRoute } from 'vue-router';

	const props = defineProps({
		isShow: { type: Boolean, default: false },
		isReadOnly: { type: Boolean, default: true },
		handleType: { type: String, default: '' },
		currentRow: { type: Object },
	});

	let route = useRoute();
	let store = useStore();
	const curDrawerSize = ref(store.state.uiDrawerSizeBig);

	let dictObj = store.getters.getDictObj(['BUILDING_LEVEL']);
	const tableRef = ref();
	//查询条件
	let queryParams = reactive({ deviceName: '', floorNum: '', deviceLocation: '' });
	//抽屉flag
	let isShowDrawer = ref(props.isShow);
	// 列表 filed
	let tableData = reactive({
		loading: false,
		data: [],
	});

	watch(
		() => props.isShow,
		(newVal, oldVal) => {
			isShowDrawer.value = newVal;
			if (newVal) {
				for (let i in queryParams) {
					queryParams[i] = '';
				}
			}
			nextTick(() => {
				newVal && ['info', 'edit'].includes(props.handleType) && queryList('init');
			});
		},
	);

	const emit = defineEmits(['close']);

	// 列表数据源 | 返显
	const queryList = async init => {
		if (process.env.NODE_ENV !== 'development') {
			let portalResourceList = JSON.parse(localStorage.getItem('portalResourceList'));
			if (init != 'init' && !portalResourceList.includes('p_btn_property_maintenance_facility_config_list_query')) return;
		}
		tableData.loading = true;
		let params = Object.assign(queryParams);
		params.planId = props.currentRow?.id;
		params.inventoryId = props.currentRow?.inventoryId;
		params.projectCode = route.query.projectCode;
		let res = await planFacilityListApi(queryParams);
		if (res.data.code !== 200) return;
		tableData.loading = false;
		tableData.data = res.data.data || [];
		let chooseList = tableData.data.filter(item => item.isBind);
		nextTick(() => {
			chooseList.forEach(v => {
				tableRef.value.toggleRowSelection(v, true);
			});
			hideSelectAllBtn();
		});
	};

	//设置禁用状态
	const isSelectable = (row, index) => {
		return props.handleType == 'edit' ? true : false;
	};

	//提交
	const doConfirm = async () => {
		let ids = chooseTagList.value.map(item => item.facilityId);
		let params = { facilityIds: ids, maintenanceId: props.currentRow?.id };
		let res = await planFacilityBindApi(params);
		if (res.data.code !== 200) return;
		ElMessage({
			message: '提交成功',
			type: 'success',
		});
		isShowDrawer.value = false;
		emit('close', { isShow: false, isRefresh: true });
	};

	//选择
	let chooseTagList = ref([]);
	const handleSelectionChange = data => {
		chooseTagList.value = data;
	};

	//关闭抽屉
	const handleClose = done => {
		emit('close', { isShow: false });
		done();
	};

	//显示｜ 隐藏全选按钮
	const hideSelectAllBtn = () => {
		if (tableRef.value) {
			const checkboxCell = tableRef.value.$el.querySelector('.el-table__header th:first-child .cell');
			if (checkboxCell) {
				checkboxCell.style.display = props.handleType == 'info' ? 'none' : 'inline-flex';
			}
		}
	};
</script>
